package com.halko.PR.pr.svm;

import static org.bytedeco.javacpp.opencv_core.merge;
import static org.bytedeco.javacpp.opencv_core.split;
import static org.bytedeco.javacpp.opencv_imgproc.CV_BGR2HSV;
import static org.bytedeco.javacpp.opencv_imgproc.CV_HSV2BGR;
import static org.bytedeco.javacpp.opencv_imgproc.CV_RGB2GRAY;
import static org.bytedeco.javacpp.opencv_imgproc.CV_THRESH_BINARY;
import static org.bytedeco.javacpp.opencv_imgproc.CV_THRESH_OTSU;
import static org.bytedeco.javacpp.opencv_imgproc.cvtColor;
import static org.bytedeco.javacpp.opencv_imgproc.equalizeHist;
import static org.bytedeco.javacpp.opencv_imgproc.threshold;

import com.halko.PR.pr.core.CoreFunc;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_core.MatVector;


/**
 * @author halko
 * @create 2021-03-23 20:22
 */
public class Features implements SVMCallback {

    CoreFunc coreFunc = new CoreFunc();

    /**
     * 本函数是生成直方图均衡特征的回调函数
     */
    @Override
    public opencv_core.Mat getHisteqFeatures(opencv_core.Mat image) {
        Mat out = new Mat(image.size(), image.type());
        if (image.channels() == 3) {
            Mat hsv = new Mat();
            MatVector hsvSplit = new MatVector();
            cvtColor(image, hsv, CV_BGR2HSV);
            split(hsv, hsvSplit);
            // 通过对直方图进行归一化，对灰度图像的亮度和对比度进行归一化
            equalizeHist(hsvSplit.get(2), hsvSplit.get(2));
            merge(hsvSplit, hsv);
            cvtColor(hsv, out, CV_HSV2BGR);
            System.gc();
        } else if (image.channels() == 1) {
            equalizeHist(image, out);
        }
        return out;
    }

    /**
     * 本函数是获取垂直和水平的直方图图值
     */
    @Override
    public opencv_core.Mat getHistogramFeatures(opencv_core.Mat image) {
        Mat grayImage = new Mat();
        cvtColor(image, grayImage, CV_RGB2GRAY);

        Mat img_threshold = new Mat();
        threshold(grayImage, img_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY);

        return coreFunc.features(img_threshold, 0);
    }
}
